package com.shop.shopserver.sender;

import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.shop.shopcommon.properties.TongyiQianwenProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Arrays;

/**
 * 向通义千问发送请求
 */
@Component
public class TongyiQianwenSender {
    @Autowired
    private TongyiQianwenProperties tongyiQianwenProperties;
    private String apiKey;
    @PostConstruct
    public void init() {
        // 确保依赖注入完成后才获取 apiKey
        if (tongyiQianwenProperties == null) {
            throw new IllegalStateException("TongyiQianwenProperties is not injected.");
        }
        this.apiKey = tongyiQianwenProperties.getApiKey();
    }

    public GenerationResult callWithMessage(String request) throws ApiException, NoApiKeyException, InputRequiredException {
        Generation gen = new Generation();
        Message systemMsg = Message.builder()
                .role(Role.SYSTEM.getValue())
                .content("你是一个营养搭配推荐师，名字叫小菜包")
                .build();
        Message userMsg = Message.builder()
                .role(Role.USER.getValue())
                .content(request)
                .build();
        GenerationParam param = GenerationParam.builder()
                // 若没有配置环境变量，请用百炼API Key将下行替换为：.apiKey("sk-xxx")
                .apiKey(apiKey)
                // 模型列表：https://help.aliyun.com/zh/model-studio/getting-started/models
                .model("qwen-plus")
                .messages(Arrays.asList(systemMsg, userMsg))
                .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                .build();
        return gen.call(param);
    }
}
